<?php
class CostpointsController extends Controller{


	public function index(){
		$this->getSmarty();
		$this->loadBasic();
		$this->smarty->display("user_center/shopping.tpl");
	}
	public function loadBasic(){
		require_once SERVICE . DS . 'CommonDataService.class.php';
		// START 数据库查询及分页数据
		$service = new CommonDataService( $this->getDB () );
		$results = $service->getResults("select * from cost_points_card");
		$user = $service->getResult("select * from users where userid='".$_SESSION['user']['userid']."'" );
		
		$user_points = $service->getResult("select sum(points) points from user_points_record where userid='".$_SESSION['user']['userid']."' and record_type = 0" );
		
		$this->smarty->assign("options",$results);
		$this->smarty->assign("earnpoints",$user_points->points);
		$this->smarty->assign("totalCount",$user->points);
	}
	
	public function apply(){
		$this->getSmarty();
		
		if(!isset($_SESSION['user'])){
			$resultMsg="Please log in first!";
			echo json_encode ( $resultMsg );
			return;
		}
		
		require_once SERVICE . DS . 'CommonDataService.class.php';
		// START 数据库查询及分页数据
		$service = new CommonDataService( $this->getDB () );
		$type = $_POST["type"];
		$result = $service->getResult("select * from cost_points_card where id='".$type."'");
		 
		if(empty($result)){
			$resultMsg="The convertible integral type was not found!";
		}else{
			$user = $service->getResult("select * from users where userid='".$_SESSION['user']['userid']."' and points >=".$result->costpoints );
			if(empty($user)){
				$resultMsg="Please choose the kind of integral to change!";
			}else{
				$service->exSql("update users set points = points -".$result->costpoints."  where userid ='".$_SESSION['user']['userid']."'" );
				
			
				$invitePointsRecord = array (
					'id' => uniqid (),
					'userid' => $_SESSION['user']['userid'],
					'username' => $_SESSION['user']['username'],
					'record_type' => 1,
					'points' => $result->costpoints,
					'points_type' => 10,
					'points_desc'=>"Approval card cost ".$result->costpoints,
					'create_time' =>date("Y-m-d h:m:s")
				);
				$service->add("user_points_record",$invitePointsRecord);
				
				
				
				$appRecord = array (
					'id' => uniqid (),
					'userid' => $_SESSION['user']['userid'],
					'username' => $_SESSION['user']['username'],
					'costpoints' => $result->costpoints,
					'card' => $result->card,
					'unit' => $result->unit,
					'state' => 0,
					'checked' => 0,
					'desc'=>"Approval card cost ".$result->costpoints,
					'create_time' =>date("Y-m-d h:m:s")
				);
				$service->add("user_points_approval_card",$appRecord);
				$resultMsg="Change is complete. We will send to your email as quick as possible, please pay attention to check!";
			}
		}
		$this->loadBasic();
//		$this->smarty->assign("resultMsg",$resultMsg);
//		$this->smarty->display("user_center/shopping.tpl");
		echo json_encode ( $resultMsg );
	}
}